package ofpof.database;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.mongodb.DB;
import com.mongodb.Mongo;

public class MongoDatabaseConnectionProvider implements DisposableBean {
	
	private static final ThreadLocal<DB> DATABASE = new ThreadLocal<DB>();
	
	@Autowired
	private MongoDatasourceFactory mongoDatasourceFactory;
	
	private String databaseName = "ofpof";
	
	public DB getCurrentConnection() {
		DB db = DATABASE.get();
		if (db == null) {
			db =  connect();
			DATABASE.set(db);
		}
		return db;
	}
	
	public DB connect() {
		Mongo mongo;
		try {
			mongo = mongoDatasourceFactory.getObject();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return mongo.getDB(databaseName);
	}
	
	public void startRequest() {
		DB db = getCurrentConnection();
		db.requestStart();
		cleanup();
	}
	
	private void cleanup() {
		DATABASE.remove();
	}
	
	public void stopRequest() {
		DB db = getCurrentConnection();
		db.requestDone();
		cleanup();
	}

	public void setDatabaseName(String databaseName) {
		this.databaseName = databaseName;
	}

	@Override
	public void destroy() throws Exception {
		cleanup();
	}
}
